﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Skugo.Core;
using Skugo.Shared;
using System.IO;
using AvalonDock;

namespace Skugo.StandardPlugins
{
    public class Console : DockablePlugin
    {
        /// <summary>
        /// The type of message we send or receieve.
        /// </summary>
        enum MessageType : byte
        {
            WriteMessage,
            UserInput,
        }

        private ConsoleForm Form;

        protected override void Initialize(BinaryReader reader)
        {
            base.Initialize(reader);

            this.Form = new ConsoleForm();
            this.Content = this.Form;

            this.Form.InputText.KeyDown += new System.Windows.Input.KeyEventHandler(InputText_KeyDown);
        }

        void InputText_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                this.Form.ConsoleText.Text += this.Form.InputText.Text + "\n";


                // Create a memory stream to write data to
                MemoryStream stream = new MemoryStream();

                // Create a binary writer to write the data
                BinaryWriter outgoing = new BinaryWriter(stream);

                // Write out a the frame buffer message
                outgoing.Write((Byte)MessageType.UserInput);

                outgoing.WriteAsciiString(this.Form.InputText.Text);

                this.Send(stream.ToArray());



                this.Form.InputText.Text = String.Empty;

                e.Handled = true;
            }
        }

        protected override void OnReceive(byte[] data)
        {
            var stream = new MemoryStream(data);

            var incoming = new BinaryReader(stream);

            var message = (MessageType)incoming.ReadByte();

            switch (message)
            {
                case MessageType.WriteMessage:
                    {
                        var text = incoming.ReadAsciiString();

                        this.Form.ConsoleText.Text += text;
                        break;
                    }
            }
        }
    }
}
